package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.model.user.dtos.UserInfoDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.invoke.LambdaMetafactory;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-09-15
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * app用户登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(AppLoginDto dto) {

        Map<String, Object> map = new HashMap<>();
        Integer userId = 0;
        if(StringUtils.isNotBlank(dto.getPhone()) &&
            StringUtils.isNotBlank(dto.getPassword())) {
//        手机号密码登录
//            根据手机号查询用户信息
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = getOne(queryWrapper);
//            如果用户不存在，抛异常
            if(apUser==null){
                log.error("没有对应的用户,phone={}",dto.getPhone());
                throw new LeadException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
//            获取加密后的密码
            String encoded = apUser.getPassword();
//            使用Bcrypt 和前端传递的密码比对
            boolean b = encoder.matches(dto.getPassword(), encoded);
//            如果密码不正确抛异常
            if(!b){
                log.error("用户密码不正确，phone={}",dto.getPhone());
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
//            把用户id赋值给userId
            userId = apUser.getId();
            map.put("user", BeanHelper.copyProperties(apUser, UserInfoDto.class));
        }else {
//        不登录先看看
//            如果没有设备号抛异常
            if(StringUtils.isBlank(dto.getEquipmentId())){
                log.error("没有设备号");
                throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
            }
        }
//        生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userId, 120);
        map.put("token",token);
        return map;
    }
}
